package nimo.elibrary.db.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import nimo.elibrary.db.DatabaseHelper;
import nimo.elibrary.json.model.book.Book;

/**
 * Created with IntelliJ IDEA.
 * User: Enkuso
 * Date: 12/11/12
 * Time: 12:53 PM
 * To change this template use File | Settings | File Templates.
 */
public class BookmarkDataSource {
    public final static int LIMIT = 10;
    // Database fields
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private String[] allcolumns = { DatabaseHelper.COLUMN_ID,
        DatabaseHelper.COLUMN_BOOKID,
        DatabaseHelper.COLUMN_BOOKTITLE,
        DatabaseHelper.COLUMN_BOOKCOVER,
        DatabaseHelper.COLUMN_BOOKDESCRIPTION };

    public BookmarkDataSource(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    public void open() throws SQLiteException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    /**
     * Bookmark жагсаалтад ном нэмэх
     *
     * @param bookId
     * @param bookTitle
     * @param bookCover
     * @param bookDescription
     * @return Амжилттай нэмсэн бол true үгүй бол (limit exceeded) false
     */
    public boolean addToBookmark(String bookId, String bookTitle, String bookCover, String bookDescription) {
        if(countBookmark() <= LIMIT) {
            if(!isBookmarked(bookId)) {
                // bookmark жагсаалтад нэмэх
                ContentValues values = new ContentValues();
                values.put(DatabaseHelper.COLUMN_BOOKID, bookId);
                values.put(DatabaseHelper.COLUMN_BOOKTITLE, bookTitle);
                values.put(DatabaseHelper.COLUMN_BOOKCOVER, bookCover);
                values.put(DatabaseHelper.COLUMN_BOOKDESCRIPTION, bookDescription);
                long insertId = database.insert(DatabaseHelper.TABLE_BOOKMARKS, null, values);
            }
            return true;
        } else {
            // Bookmark жагсаалт дүүрсэн
            return false;
        }
    }

    /**
     * Ном bookmark жагсаалтад байгаа эсэхийг шалгах
     */
    public boolean isBookmarked(String bookId) {
        Cursor cursor = database.query(DatabaseHelper.TABLE_BOOKMARKS,
                allcolumns, DatabaseHelper.COLUMN_BOOKID + " = " + bookId, null,
                null, null, null);
        cursor.moveToFirst();
        boolean result = cursor.getCount() > 0;
        cursor.close();
        return result;
    }

    /**
     * Bookmark жагсаалт дах номуудын мэдээлэл авах
     */
    public Book[] getBookmarkList() {
        Book[] books = new Book[countBookmark()];
        Cursor cursor = database.query(DatabaseHelper.TABLE_BOOKMARKS,
                allcolumns, null, null,
                null, null, null);
        cursor.moveToFirst();
        int i = 0;
        do {
            books[i] = cursorToBook(cursor);
            i++;
        } while (cursor.moveToNext());
        cursor.close();

        return books;
    }

    /**
     * Bookmark жагсаалтад хичнээн ном тэмдэглэсэн байгааг тоолох
     *
     * @return Bookmark тэмдэглэсэн номын тоо
     */
    public int countBookmark() {
        int count = 0;
        count = (int) DatabaseUtils.longForQuery(database, "SELECT count(*) FROM " + DatabaseHelper.TABLE_BOOKMARKS, null);
        return count;
    }

    /**
     * Bookmark жагсаалтаас ном хасах
     * @param bookId
     */
    public void deleteFromBookmark(String bookId) {
        database.delete(DatabaseHelper.TABLE_BOOKMARKS, DatabaseHelper.COLUMN_BOOKID + " = " + bookId, null);
    }


    private Book cursorToBook(Cursor cursor) {
        if(cursor!=null && cursor.getCount()>0) {
            Book book = new Book();
            book.id = cursor.getString(1);
            book.title = cursor.getString(2);
            book.cover = cursor.getString(3);
            book.introduction = cursor.getString(4);
            return book;
        }
        return null;
    }

    /**
     * Bookmark жагсаалт дах нэг номын мэдээлэл авах
     */
    public Book getBook(String bookId) {
        Book book = null;
        Cursor cursor = database.query(DatabaseHelper.TABLE_BOOKMARKS,
                allcolumns, DatabaseHelper.COLUMN_BOOKID + " = " + bookId, null,
                null, null, null);
        cursor.moveToFirst();
        if(cursor.getCount() > 0)
            book = cursorToBook(cursor);
        cursor.close();
        return book;
    }
}
